{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8de56b32-bec3-47a4-afd6-186736ab5500",
   "metadata": {},
   "source": [
    "DataFrame\n",
    "是一个表格型数据结构，既有行标签（index），又有列标签（columns），它也被称为异构数据表，所谓异构，指的是表格中每列的数据类型可以不同，比如说可以是字符串、整型或者浮点型。\n",
    "dataframe的每一行数据都可以看成一个series结构，只不过，dataframe为这些行中每个数据增加一个列标签，因此，dataframe其实是从series的基础上演变而来的，在数据分析任务中dataframe的应用非常广泛，因此它描述数据的更为清晰、直观。dataframe结构类似于excel的表格型。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ffd25bbf-57b0-45c0-abd8-01ddfff02c94",
   "metadata": {},
   "source": [
    "创建dataframe对象\n",
    "格式为\n",
    "import pandas as pd\n",
    "pd.DataFrame(data,index,columns,dtype,copy)\n",
    "data：输入的数据，可以是ndarry，series，list，dict，标量以及一个dataframe\n",
    "index：行标签，如果没有传递index值，则默认行标签是np.arange（n），n代表data元素个数\n",
    "columns：列标签，如果没有传递columns值，则默认列标签是np.arange（n）\n",
    "dtype：表示每一列的数据类型\n",
    "copy：默认为false，表示复制数据data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "40cec04a-3e88-4959-9079-c07a8d762155",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Empty DataFrame\n",
      "Columns: []\n",
      "Index: []\n"
     ]
    }
   ],
   "source": [
    "# 1）创建空的dataframe对象\n",
    "import pandas as pd\n",
    "df = pd.DataFrame()\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2b508f16-188c-4717-8543-1bb280570b33",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   0\n",
      "0  1\n",
      "1  2\n",
      "2  3\n",
      "3  4\n",
      "4  5\n"
     ]
    }
   ],
   "source": [
    "# 2）列表创建dataframe对象\n",
    "# 单一列表创建dataframe对象\n",
    "import pandas as pd\n",
    "data = [1,2,3,4,5]\n",
    "df = pd.DataFrame(data)\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "8625cf9c-7e0f-4c02-9ee2-e96690278e83",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      name  age\n",
      "0     alex   10\n",
      "1  freeman   12\n",
      "2   clarke   13\n"
     ]
    }
   ],
   "source": [
    "# 3）使用嵌套列表创建dataframe对象\n",
    "import pandas as pd\n",
    "data = [['alex',10],['freeman',12],['clarke',13]]\n",
    "df = pd.DataFrame(data,columns=['name','age'])\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "89a415d2-1c5a-4e49-b0c1-3886f671af58",
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "could not convert string to float: 'alex'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[11], line 4\u001b[0m\n\u001b[0;32m      2\u001b[0m \u001b[38;5;28;01mimport\u001b[39;00m \u001b[38;5;21;01mpandas\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m \u001b[38;5;21;01mpd\u001b[39;00m\n\u001b[0;32m      3\u001b[0m data \u001b[38;5;241m=\u001b[39m [[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124malex\u001b[39m\u001b[38;5;124m'\u001b[39m,\u001b[38;5;241m10\u001b[39m],[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mfreeman\u001b[39m\u001b[38;5;124m'\u001b[39m,\u001b[38;5;241m12\u001b[39m],[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mclarke\u001b[39m\u001b[38;5;124m'\u001b[39m,\u001b[38;5;241m13\u001b[39m]]\n\u001b[1;32m----> 4\u001b[0m df \u001b[38;5;241m=\u001b[39m pd\u001b[38;5;241m.\u001b[39mDataFrame(data,columns\u001b[38;5;241m=\u001b[39m[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mname\u001b[39m\u001b[38;5;124m'\u001b[39m,\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mage\u001b[39m\u001b[38;5;124m'\u001b[39m],dtype \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mfloat\u001b[39m)\n\u001b[0;32m      5\u001b[0m \u001b[38;5;28mprint\u001b[39m(df)\n",
      "File \u001b[1;32mD:\\anaconda3\\Lib\\site-packages\\pandas\\core\\frame.py:859\u001b[0m, in \u001b[0;36mDataFrame.__init__\u001b[1;34m(self, data, index, columns, dtype, copy)\u001b[0m\n\u001b[0;32m    850\u001b[0m         columns \u001b[38;5;241m=\u001b[39m ensure_index(columns)\n\u001b[0;32m    851\u001b[0m     arrays, columns, index \u001b[38;5;241m=\u001b[39m nested_data_to_arrays(\n\u001b[0;32m    852\u001b[0m         \u001b[38;5;66;03m# error: Argument 3 to \"nested_data_to_arrays\" has incompatible\u001b[39;00m\n\u001b[0;32m    853\u001b[0m         \u001b[38;5;66;03m# type \"Optional[Collection[Any]]\"; expected \"Optional[Index]\"\u001b[39;00m\n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m    857\u001b[0m         dtype,\n\u001b[0;32m    858\u001b[0m     )\n\u001b[1;32m--> 859\u001b[0m     mgr \u001b[38;5;241m=\u001b[39m arrays_to_mgr(\n\u001b[0;32m    860\u001b[0m         arrays,\n\u001b[0;32m    861\u001b[0m         columns,\n\u001b[0;32m    862\u001b[0m         index,\n\u001b[0;32m    863\u001b[0m         dtype\u001b[38;5;241m=\u001b[39mdtype,\n\u001b[0;32m    864\u001b[0m         typ\u001b[38;5;241m=\u001b[39mmanager,\n\u001b[0;32m    865\u001b[0m     )\n\u001b[0;32m    866\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m    867\u001b[0m     mgr \u001b[38;5;241m=\u001b[39m ndarray_to_mgr(\n\u001b[0;32m    868\u001b[0m         data,\n\u001b[0;32m    869\u001b[0m         index,\n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m    873\u001b[0m         typ\u001b[38;5;241m=\u001b[39mmanager,\n\u001b[0;32m    874\u001b[0m     )\n",
      "File \u001b[1;32mD:\\anaconda3\\Lib\\site-packages\\pandas\\core\\internals\\construction.py:119\u001b[0m, in \u001b[0;36marrays_to_mgr\u001b[1;34m(arrays, columns, index, dtype, verify_integrity, typ, consolidate)\u001b[0m\n\u001b[0;32m    116\u001b[0m         index \u001b[38;5;241m=\u001b[39m ensure_index(index)\n\u001b[0;32m    118\u001b[0m     \u001b[38;5;66;03m# don't force copy because getting jammed in an ndarray anyway\u001b[39;00m\n\u001b[1;32m--> 119\u001b[0m     arrays, refs \u001b[38;5;241m=\u001b[39m _homogenize(arrays, index, dtype)\n\u001b[0;32m    120\u001b[0m     \u001b[38;5;66;03m# _homogenize ensures\u001b[39;00m\n\u001b[0;32m    121\u001b[0m     \u001b[38;5;66;03m#  - all(len(x) == len(index) for x in arrays)\u001b[39;00m\n\u001b[0;32m    122\u001b[0m     \u001b[38;5;66;03m#  - all(x.ndim == 1 for x in arrays)\u001b[39;00m\n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m    125\u001b[0m \n\u001b[0;32m    126\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m    127\u001b[0m     index \u001b[38;5;241m=\u001b[39m ensure_index(index)\n",
      "File \u001b[1;32mD:\\anaconda3\\Lib\\site-packages\\pandas\\core\\internals\\construction.py:629\u001b[0m, in \u001b[0;36m_homogenize\u001b[1;34m(data, index, dtype)\u001b[0m\n\u001b[0;32m    626\u001b[0m         val \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mdict\u001b[39m(val)\n\u001b[0;32m    627\u001b[0m     val \u001b[38;5;241m=\u001b[39m lib\u001b[38;5;241m.\u001b[39mfast_multiget(val, oindex\u001b[38;5;241m.\u001b[39m_values, default\u001b[38;5;241m=\u001b[39mnp\u001b[38;5;241m.\u001b[39mnan)\n\u001b[1;32m--> 629\u001b[0m val \u001b[38;5;241m=\u001b[39m sanitize_array(val, index, dtype\u001b[38;5;241m=\u001b[39mdtype, copy\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m)\n\u001b[0;32m    630\u001b[0m com\u001b[38;5;241m.\u001b[39mrequire_length_match(val, index)\n\u001b[0;32m    631\u001b[0m refs\u001b[38;5;241m.\u001b[39mappend(\u001b[38;5;28;01mNone\u001b[39;00m)\n",
      "File \u001b[1;32mD:\\anaconda3\\Lib\\site-packages\\pandas\\core\\construction.py:625\u001b[0m, in \u001b[0;36msanitize_array\u001b[1;34m(data, index, dtype, copy, allow_2d)\u001b[0m\n\u001b[0;32m    621\u001b[0m             subarr \u001b[38;5;241m=\u001b[39m subarr\u001b[38;5;241m.\u001b[39mcopy()\n\u001b[0;32m    623\u001b[0m     \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m    624\u001b[0m         \u001b[38;5;66;03m# we will try to copy by-definition here\u001b[39;00m\n\u001b[1;32m--> 625\u001b[0m         subarr \u001b[38;5;241m=\u001b[39m _try_cast(data, dtype, copy)\n\u001b[0;32m    627\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m \u001b[38;5;28mhasattr\u001b[39m(data, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124m__array__\u001b[39m\u001b[38;5;124m\"\u001b[39m):\n\u001b[0;32m    628\u001b[0m     \u001b[38;5;66;03m# e.g. dask array GH#38645\u001b[39;00m\n\u001b[0;32m    629\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m copy:\n",
      "File \u001b[1;32mD:\\anaconda3\\Lib\\site-packages\\pandas\\core\\construction.py:820\u001b[0m, in \u001b[0;36m_try_cast\u001b[1;34m(arr, dtype, copy)\u001b[0m\n\u001b[0;32m    818\u001b[0m     subarr \u001b[38;5;241m=\u001b[39m maybe_cast_to_integer_array(arr, dtype)\n\u001b[0;32m    819\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m copy:\n\u001b[1;32m--> 820\u001b[0m     subarr \u001b[38;5;241m=\u001b[39m np\u001b[38;5;241m.\u001b[39masarray(arr, dtype\u001b[38;5;241m=\u001b[39mdtype)\n\u001b[0;32m    821\u001b[0m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[0;32m    822\u001b[0m     subarr \u001b[38;5;241m=\u001b[39m np\u001b[38;5;241m.\u001b[39marray(arr, dtype\u001b[38;5;241m=\u001b[39mdtype, copy\u001b[38;5;241m=\u001b[39mcopy)\n",
      "\u001b[1;31mValueError\u001b[0m: could not convert string to float: 'alex'"
     ]
    }
   ],
   "source": [
    "# 指定数值元素的数据，例如类型为float\n",
    "import pandas as pd\n",
    "data = [['alex',10],['freeman',12],['clarke',13]]\n",
    "df = pd.DataFrame(data,columns=['name','age'],dtype = float)\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "504245df-efb5-4cd3-ab31-fa1972864c93",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     name  age\n",
      "0     tom   20\n",
      "1   jerry   85\n",
      "2   steve   63\n",
      "3  rabbit   42\n"
     ]
    }
   ],
   "source": [
    "# 4）字典嵌套列表创建\n",
    "\"\"\" 字典中建对应的值的元素必须相同（也就是列表的长度相同）如果传递了索引，那么索引的长度应该等于数组的长度\n",
    "如果内有传递索引，那么默认情况，索引将是range（n），其中n代表数组长度 \"\"\"\n",
    "import pandas as pd\n",
    "data = {'name':['tom','jerry','steve','rabbit'],'age':[20,85,63,42]}\n",
    "df = pd.DataFrame(data)\n",
    "print(df)   # 这里使用了默认的标签，也就是range（n）生成了0，1，2，3并分别对应了列表中的元素值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "3212ebe5-845f-4a9b-92a4-019cd0ddd535",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "         name  age\n",
      "动漫人物1     tom   20\n",
      "动漫人物2   jerry   85\n",
      "动漫人物3   steve   63\n",
      "动漫人物4  rabbit   42\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "data = {'name':['tom','jerry','steve','rabbit'],'age':[20,85,63,42]}\n",
    "df = pd.DataFrame(data,index=['动漫人物1','动漫人物2','动漫人物3','动漫人物4'])\n",
    "print(df)  # index参数为每行分配一个索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "e44a2d26-7a36-4b19-a57b-0d94cfc1ae72",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   half-life2  combie  alex\n",
      "0           1       2   NaN\n",
      "1           5      10  21.0\n"
     ]
    }
   ],
   "source": [
    "# 5）列表嵌套字典创建dataframe对象 默认情况，字典的键被用作列名\n",
    "import pandas as pd\n",
    "data = [{'half-life2':1,'combie':2},{'half-life2':5,'combie':10,'alex':21}]\n",
    "df = pd.DataFrame(data)\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "492afa35-5cd2-49f1-b524-b92bd67e3f4b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     half-life2  combie  alex\n",
      "第一部           1       2   NaN\n",
      "第二部           5      10  21.0\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "data = [{'half-life2':1,'combie':2},{'half-life2':5,'combie':10,'alex':21}]\n",
    "df = pd.DataFrame(data,index=['第一部','第二部'])\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f31509c0-f9b6-4338-a17a-eff5fb704da2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     戈登 弗里曼  艾利克斯 凡思\n",
      "第一部       1        2\n",
      "第二部       5       10\n",
      "     戈登 弗里曼  艾利克斯麻省理工学院毕业生\n",
      "第一部       1            NaN\n",
      "第二部       5            NaN\n"
     ]
    }
   ],
   "source": [
    "# 6）如何使用字典嵌套列表以及行，列索引创建一个dataframe对象\n",
    "import pandas as pd\n",
    "data = [{'戈登 弗里曼':1,'艾利克斯 凡思':2},{'戈登 弗里曼':5,'艾利克斯 凡思':10,'伊莱 凡思':20}]\n",
    "df2 = pd.DataFrame(data,index=['第一部','第二部'],\n",
    "columns = ['戈登 弗里曼','艾利克斯 凡思'])\n",
    "\n",
    "df1 = pd.DataFrame(data,index=['第一部','第二部'],\n",
    "columns = ['戈登 弗里曼','艾利克斯麻省理工学院毕业生'] )\n",
    "\n",
    "print(df2)\n",
    "print(df1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "72f2b6b6-7492-4345-9dff-035a8f6fae91",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "               one  two\n",
      "中美ai竞争         1.0  1.0\n",
      "美国隐形战衣应用2055年  3.0  NaN\n",
      "贸易战            2.0  2.0\n",
      "马斯克脑机接口实现      NaN  3.0\n"
     ]
    }
   ],
   "source": [
    "# 7）series创建dataframe对象\n",
    "import pandas as pd\n",
    "d = {'one':pd.Series([1,2,3],index=['中美ai竞争','贸易战','美国隐形战衣应用2055年']),\n",
    "    'two':pd.Series([1,2,3],index=['中美ai竞争','贸易战','马斯克脑机接口实现'])}\n",
    "df = pd.DataFrame(d)\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "286d5e37-6e1a-40c6-95ae-c2a3342df55d",
   "metadata": {},
   "source": [
    "列表索引操作dataframe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c203bfdb-7f8d-4641-a2b9-5dbbb8bbf50b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     金牌   银牌\n",
      "射击  1.0  1.0\n",
      "游泳  2.0  NaN\n",
      "网球  NaN  3.0\n",
      "跳水  3.0  2.0\n",
      "射击    1.0\n",
      "游泳    2.0\n",
      "网球    NaN\n",
      "跳水    3.0\n",
      "Name: 金牌, dtype: float64\n"
     ]
    }
   ],
   "source": [
    "# 1）列索引选取数据列\n",
    "import pandas as pd\n",
    "d = {'金牌':pd.Series([1,2,3],index=['射击','游泳','跳水']),'银牌':pd.Series([1,2,3],index=['射击','跳水','网球'])}\n",
    "df = pd.DataFrame(d)\n",
    "print(df)\n",
    "print(df['金牌'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "24ff526e-d94b-48e4-a63c-f354ee752398",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       函数  概率论  数学必备知识\n",
      "函数基础一   1    1      10\n",
      "函数基础二   2    2      20\n",
      "函数基础三   3    3      30\n",
      "       函数  概率论  数学必备知识  考核\n",
      "函数基础一   1    1      10  11\n",
      "函数基础二   2    2      20  22\n",
      "函数基础三   3    3      30  33\n"
     ]
    }
   ],
   "source": [
    "# 2）列索引添加数据列   使用columns列索引可以实现添加新的数据列\n",
    "import pandas as pd\n",
    "d = {'函数':pd.Series([1,2,3],index=['函数基础一','函数基础二','函数基础三']),\n",
    "    '概率论':pd.Series([1,2,3],index=['函数基础一','函数基础二','函数基础三'])}\n",
    "df = pd.DataFrame(d)\n",
    "\n",
    "# 使用df['列']=值的方式，插入新的数据列\n",
    "df['数学必备知识'] = pd.Series([10,20,30],index=['函数基础一','函数基础二','函数基础三'])\n",
    "print(df)\n",
    "\n",
    "# 将已经存在的数据列做相加运算\n",
    "df['考核'] = df['函数'] + df['数学必备知识']\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "264d0d8a-1010-4fab-896e-40f3a14c9310",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   name  age\n",
      "0  jack   18\n",
      "1  alen   19\n",
      "2  john   20\n",
      "   name  score  age\n",
      "0  jack      1   18\n",
      "1  alen      2   19\n",
      "2  john      3   20\n"
     ]
    }
   ],
   "source": [
    "# 使用dataframe的算术运算，这和numpy非常相似，还可以使用insert（）函数插入新的数据列\n",
    "import pandas as pd\n",
    "info = [['jack',18],['alen',19],['john',20]]\n",
    "df = pd.DataFrame(info,columns=['name','age'])\n",
    "print(df)\n",
    "\n",
    "# 注意columns参数\n",
    "# 数值1代表插入到columns列表的索引位置\n",
    "df.insert(1,column='score',value=[1,2,3])\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "4b178d2b-efd1-459b-9861-57bf3839387e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     金牌   银牌    铜牌\n",
      "射击  1.0  1.0  10.0\n",
      "游泳  2.0  NaN  20.0\n",
      "网球  NaN  3.0   NaN\n",
      "跳水  3.0  2.0  30.0\n",
      "     金牌   银牌\n",
      "射击  1.0  1.0\n",
      "游泳  2.0  NaN\n",
      "网球  NaN  3.0\n",
      "跳水  3.0  2.0\n"
     ]
    },
    {
     "ename": "NameError",
     "evalue": "name 'pop' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[19], line 15\u001b[0m\n\u001b[0;32m     12\u001b[0m \u001b[38;5;28mprint\u001b[39m(df)\n\u001b[0;32m     14\u001b[0m \u001b[38;5;66;03m# 使用pop删除\u001b[39;00m\n\u001b[1;32m---> 15\u001b[0m pop\u001b[38;5;241m.\u001b[39mdf[\u001b[38;5;124m'\u001b[39m\u001b[38;5;124m银牌\u001b[39m\u001b[38;5;124m'\u001b[39m]\n\u001b[0;32m     16\u001b[0m \u001b[38;5;28mprint\u001b[39m(df)\n",
      "\u001b[1;31mNameError\u001b[0m: name 'pop' is not defined"
     ]
    }
   ],
   "source": [
    "# 3）列索引删除数据列\n",
    "# 通过del和pop删除dataframe中的数据列\n",
    "import pandas as pd\n",
    "d = {'金牌':pd.Series([1,2,3],index=['射击','游泳','跳水']),\n",
    "     '银牌':pd.Series([1,2,3],index=['射击','跳水','网球']),\n",
    "     '铜牌':pd.Series([10,20,30],index=['射击','游泳','跳水'])}\n",
    "df = pd.DataFrame(d)\n",
    "print(df)\n",
    "\n",
    "# 使用del删除\n",
    "del df['铜牌']\n",
    "print(df)\n",
    "\n",
    "# 使用pop删除\n",
    "pop.df['银牌']\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ba2d260-df49-4e34-9b36-bf0654fa4e1a",
   "metadata": {},
   "source": [
    "行索引操作dataframe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "c57573e9-1b35-4d81-8061-53a404392ebc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     金牌   银牌    铜牌\n",
      "射击  1.0  1.0  10.0\n",
      "游泳  2.0  NaN  20.0\n",
      "网球  NaN  3.0   NaN\n",
      "跳水  3.0  2.0  30.0\n",
      "金牌     2.0\n",
      "银牌     NaN\n",
      "铜牌    20.0\n",
      "Name: 游泳, dtype: float64\n"
     ]
    }
   ],
   "source": [
    "# 1）标签索引选取  可以将行标签传递给loc函数，来选取数据\n",
    "import pandas as pd\n",
    "d = {'金牌':pd.Series([1,2,3],index=['射击','游泳','跳水']),\n",
    "     '银牌':pd.Series([1,2,3],index=['射击','跳水','网球']),\n",
    "     '铜牌':pd.Series([10,20,30],index=['射击','游泳','跳水'])}\n",
    "df = pd.DataFrame(d)\n",
    "print(df)\n",
    "print(df.loc['游泳'])\n",
    "\n",
    "# 注意：loc值允许接两个参数分别是行和列，参数之间需要使用逗号隔开，但该函数只能接收标签索引"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "ca1ba65b-6f61-4550-b481-e0b0f192c942",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     金牌   银牌    铜牌\n",
      "射击  1.0  1.0  10.0\n",
      "游泳  2.0  NaN  20.0\n",
      "网球  NaN  3.0   NaN\n",
      "跳水  3.0  2.0  30.0\n",
      "金牌    NaN\n",
      "银牌    3.0\n",
      "铜牌    NaN\n",
      "Name: 网球, dtype: float64\n"
     ]
    }
   ],
   "source": [
    "# 整数索引选取 \n",
    "# 通过将数据所在的索引位置传递给iloc函数，同样可以实现数据行选取\n",
    "import pandas as pd\n",
    "d = {'金牌':pd.Series([1,2,3],index=['射击','游泳','跳水']),\n",
    "     '银牌':pd.Series([1,2,3],index=['射击','跳水','网球']),\n",
    "     '铜牌':pd.Series([10,20,30],index=['射击','游泳','跳水'])}\n",
    "df = pd.DataFrame(d)\n",
    "print(df)\n",
    "print(df.iloc[2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "a3644878-3606-45da-b21f-0e086c3cd365",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     金牌   银牌    铜牌\n",
      "射击  1.0  1.0  10.0\n",
      "游泳  2.0  NaN  20.0\n",
      "网球  NaN  3.0   NaN\n",
      "跳水  3.0  2.0  30.0\n",
      "     金牌   银牌    铜牌\n",
      "网球  NaN  3.0   NaN\n",
      "跳水  3.0  2.0  30.0\n"
     ]
    }
   ],
   "source": [
    "# 切片操作多行选取\n",
    "import pandas as pd\n",
    "d = {'金牌':pd.Series([1,2,3],index=['射击','游泳','跳水']),\n",
    "     '银牌':pd.Series([1,2,3],index=['射击','跳水','网球']),\n",
    "     '铜牌':pd.Series([10,20,30],index=['射击','游泳','跳水'])}\n",
    "df = pd.DataFrame(d)\n",
    "print(df)\n",
    "\n",
    "# 左闭右开\n",
    "print(df[2:4])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b83d1b0b-717c-4d9f-86fb-18180644864f",
   "metadata": {},
   "source": [
    "添加行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "e5066f38-40e8-430f-8036-ba75b5ec768a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A  B\n",
      "0  1  2\n",
      "1  3  4\n",
      "2  5  6\n"
     ]
    }
   ],
   "source": [
    "# 使用concat（）方法完成对数据行的添加\n",
    "# coding:UTF-8\n",
    "import pandas as pd\n",
    "\n",
    "# 创建一个dataframe\n",
    "df = pd.DataFrame([[1,2],[3,4]],columns=['A','B'])\n",
    "\n",
    "# 要添加的数据行，创建一个新的dataframe\n",
    "new_df = pd.DataFrame([[5,6]],columns = ['A','B'])\n",
    "\n",
    "# 使用pd.concat（）合并\n",
    "df = pd.concat([df,new_df],ignore_index = True)\n",
    "\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "9ea1f12c-13ec-4dc4-afc8-b9a961111b29",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A  B\n",
      "0  1  2\n",
      "1  3  4\n",
      "2  5  6\n"
     ]
    }
   ],
   "source": [
    "# 如果需要添加单个行，则可以使用loc（）方法进行\n",
    "import pandas as pd\n",
    "\n",
    "# 创建一个dataframe\n",
    "df = pd.DataFrame([[1,2],[3,4]],columns=['A','B'])\n",
    "\n",
    "# 直接使用loc（）的方法添加新行\n",
    "df.loc[len(df)] = [5,6]\n",
    "\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "3132feaa-be82-41c8-853d-22e4fab7ccd9",
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'DataFrame' object has no attribute 'append'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_2600\\197252124.py\u001b[0m in \u001b[0;36m?\u001b[1;34m()\u001b[0m\n\u001b[0;32m      7\u001b[0m \u001b[1;31m# 要添加的新行\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      8\u001b[0m \u001b[0mnew_row\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m{\u001b[0m\u001b[1;34m'A'\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;36m5\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'B'\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;36m6\u001b[0m\u001b[1;33m}\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      9\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     10\u001b[0m \u001b[1;31m# 使用append（）方法添加新行，在最新使用中会报错\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 11\u001b[1;33m \u001b[0mdf\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mdf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mnew_row\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mignore_index\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;32mTrue\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     12\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     13\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mdf\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\anaconda3\\Lib\\site-packages\\pandas\\core\\generic.py\u001b[0m in \u001b[0;36m?\u001b[1;34m(self, name)\u001b[0m\n\u001b[0;32m   6295\u001b[0m             \u001b[1;32mand\u001b[0m \u001b[0mname\u001b[0m \u001b[1;32mnot\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_accessors\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m   6296\u001b[0m             \u001b[1;32mand\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_info_axis\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m_can_hold_identifiers_and_holds_name\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mname\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m   6297\u001b[0m         \u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m   6298\u001b[0m             \u001b[1;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mname\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m-> 6299\u001b[1;33m         \u001b[1;32mreturn\u001b[0m \u001b[0mobject\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__getattribute__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mname\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mAttributeError\u001b[0m: 'DataFrame' object has no attribute 'append'"
     ]
    }
   ],
   "source": [
    "# 使用append（）方法在最新的pandas版本中不再推荐使用，但是不影响方法的正常使用\n",
    "import pandas as pd\n",
    "\n",
    "# 创建一个dataframe\n",
    "df = pd.DataFrame([[1,2],[3,4]],columns=['A','B'])\n",
    "\n",
    "# 要添加的新行\n",
    "new_row = {'A':5,'B':6}\n",
    "\n",
    "# 使用append（）方法添加新行，在最新使用中会报错\n",
    "df = df.append(new_row,ignore_index = True)\n",
    "\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e1810c4-79e0-4ab5-9876-a8fe5de970fe",
   "metadata": {},
   "source": [
    "添加列"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "ad112409-6da9-432b-8fc6-008c416963b9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A  B  C\n",
      "0  1  4  7\n",
      "1  2  5  8\n",
      "2  3  6  9\n"
     ]
    }
   ],
   "source": [
    "# 直接赋值，如果列不存在，pandas会自动创建列\n",
    "import pandas as pd\n",
    "\n",
    "# 创建一个dataframe\n",
    "df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})\n",
    "\n",
    "# 添加新列c\n",
    "df['C'] = [7,8,9]\n",
    "\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "2efcc9f1-f7ed-4c5a-aab3-8577da106493",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A  B  C  D\n",
      "0  1  4  7  5\n",
      "1  2  5  8  7\n",
      "2  3  6  9  9\n"
     ]
    }
   ],
   "source": [
    "# 使用assign（）方法  assign() 方法可以创建新的列，并且返回一个新的dataframe，这种方法的好处是可以在一次中调用中添加多个列\n",
    "import pandas as pd\n",
    "\n",
    "# 创建一个dataframe\n",
    "df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})\n",
    "\n",
    "# 使用assign（）的方法添加新列c和d\n",
    "df = df.assign(C = [7,8,9],D = lambda x: x['A'] + x['B'])\n",
    "\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "0ef94154-07de-4c6f-8222-6f6921c7bef3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A  C  B\n",
      "0  1  7  4\n",
      "1  2  8  5\n",
      "2  3  9  6\n"
     ]
    }
   ],
   "source": [
    "# 使用insert（）方法  insert允许在指定位置插入新列\n",
    "import pandas as pd\n",
    "\n",
    "# 创建一个dataframe\n",
    "df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})\n",
    "\n",
    "# 在1的位置插入新列\n",
    "df.insert(1,'C',[7,8,9])\n",
    "\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "94820547-0334-4245-8c55-6e8c1a84ab8f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A  B   C\n",
      "0  1  4   4\n",
      "1  2  5  10\n",
      "2  3  6  18\n"
     ]
    }
   ],
   "source": [
    "# 使用apply（）方法 apply可以用来根据现有列计算新列的位置\n",
    "import pandas as pd\n",
    "\n",
    "# 创建一个dataframe\n",
    "df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})\n",
    "\n",
    "# 使用apply方法添加新列c，其值为a和b的乘积\n",
    "df['C'] = df.apply(lambda row:row['A']*row['B'],axis=1)\n",
    "\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "f5c604e2-c0ab-4195-9c42-65311055696e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A  B     C\n",
      "0  1  4  0.25\n",
      "1  2  5  0.40\n",
      "2  3  6  0.50\n"
     ]
    }
   ],
   "source": [
    "# 使用eval（）方法  eval可以用来执行字符串表达式，从而创建新的列\n",
    "import pandas as pd\n",
    "\n",
    "# 创建一个dataframe\n",
    "df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})\n",
    "\n",
    "# 使用eval添加新的列c，其值为a和b的商\n",
    "df['C'] = df.eval('A/B')  # A/B保留小数，A//B保留整数\n",
    "\n",
    "print(df)\n",
    "\n",
    "# 通过结果可以看出，eval可以直接识别字符串中+、-、*、/等各种计算"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "33a0ca04-69f7-450b-bfc4-708c3c715aea",
   "metadata": {},
   "source": [
    "删除行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "e4bef7fe-d68a-40bf-9dae-bc58d288d072",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   a  b\n",
      "0  1  2\n",
      "1  3  4\n",
      "2  5  6\n",
      "3  7  8\n",
      "   a  b\n",
      "1  3  4\n",
      "2  5  6\n",
      "3  7  8\n"
     ]
    }
   ],
   "source": [
    "# 可以使用行索引标签，从dataframe中删除行数据  drop(0)\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.DataFrame([[1,2],[3,4]],columns=['a','b'])\n",
    "df2 = pd.DataFrame([[5,6],[7,8]],columns=['a','b'])\n",
    "\n",
    "df =  pd.concat([df,df2],ignore_index=True) # 添加行，把df和df2合并\n",
    "print(df)\n",
    "\n",
    "# 调用drop（）方法\n",
    "df = df.drop(0)\n",
    "print(df)\n",
    "# 通过使用drop方法，传入要删除的索引进行删除"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "eed1e180-a461-4234-8e08-b79efe17029c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     A  B   C\n",
      "第一行  1  5   9\n",
      "第二行  2  6  10\n",
      "第三行  3  7  11\n",
      "第四行  4  8  12\n",
      "     A  B   C\n",
      "第一行  1  5   9\n",
      "第四行  4  8  12\n"
     ]
    }
   ],
   "source": [
    "# 删除多行  \n",
    "import pandas as pd\n",
    "\n",
    "df = pd.DataFrame({'A':[1,2,3,4],'B':[5,6,7,8],'C':[9,10,11,12]},index=['第一行','第二行','第三行','第四行'])\n",
    "print(df)\n",
    "\n",
    "# 删除索引为 第二行 第三行 的行\n",
    "df = df.drop(['第二行','第三行'])\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "2216d515-41ee-4cc1-acb9-408468266407",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A  B   C\n",
      "0  1  5   9\n",
      "1  2  6  10\n",
      "2  3  7  11\n",
      "3  4  8  12\n",
      "   A  B   C\n",
      "2  3  7  11\n",
      "3  4  8  12\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "df = pd.DataFrame({'A':[1,2,3,4],'B':[5,6,7,8],'C':[9,10,11,12]})\n",
    "print(df)\n",
    "df = df.drop([0,1])\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "df7dc72e-e931-45b9-95dd-b6498bcb1b34",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A  B   C\n",
      "0  1  5   9\n",
      "1  2  6  10\n"
     ]
    }
   ],
   "source": [
    "# 使用布尔值索引  \n",
    "import pandas as pd\n",
    "\n",
    "df = pd.DataFrame({'A':[1,2,3,4],'B':[5,6,7,8],'C':[9,10,11,12]})\n",
    "\n",
    "# 删除A列值大于2的行\n",
    "df = df[df['A'] <= 2]\n",
    "print(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "8ab407d9-d979-480f-9c27-3140a5298cae",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A  B   C\n",
      "0  1  5   9\n",
      "1  2  6  10\n"
     ]
    }
   ],
   "source": [
    "# 使用query方法  query可以用来根据条件删除行\n",
    "import pandas as pd\n",
    "\n",
    "df = pd.DataFrame({'A':[1,2,3,4],'B':[5,6,7,8],'C':[9,10,11,12]})\n",
    "\n",
    "# 删除A列值大于2的行\n",
    "df = df.query('A<=2')\n",
    "print(df)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
